package com.leo.chapter07;

import java.io.File;
import java.io.FileFilter;
import java.util.concurrent.BlockingQueue;

/**
 * 通过 毒丸 对象来关闭服务
 * @author xuexiaolei
 * @version 2017年10月16日
 */
public class IndexingService {
    private static final File POISON = new File("");//毒丸
    private final IndexerThread consumer = new IndexerThread();
    private final CrawlerThread producer = new CrawlerThread();
    private final BlockingQueue<File> queue;
    private final FileFilter fileFilter;
    private final File root;

    public IndexingService(BlockingQueue<File> queue, FileFilter fileFilter, File root) {
        this.queue = queue;
        this.fileFilter = fileFilter;
        this.root = root;
    }

    public void start(){
        producer.start();
        consumer.start();
    }
    public void stop(){
        producer.interrupt();
    }
    public void awaitTermination() throws InterruptedException{
        consumer.join();
    }

    //生产者
    class CrawlerThread extends Thread{
        @Override
        public void run(){
            try {
                crawl(root);
            } catch (InterruptedException e) {
                /* 发生异常 */
            } finally {
                while (true){
                    try {
                        queue.put(POISON);
                        break;
                    } catch (InterruptedException e) {
                        /* 重新尝试 */
                    }
                }
            }
        }

        private void crawl(File root) throws InterruptedException {}
    }

    //消费者
    class IndexerThread extends Thread{
        @Override
        public void run(){
            try {
                while (true){
                    File file = queue.take();
                    if (file == POISON) {
                        break;
                    } else {
                        indexFile(file);
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        private void indexFile(File file) { }
    }
}
